package com.cmcc.aregister.cs.constant;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.TrafficStats;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;

import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpConnection;
import com.cmcc.aregister.cs.model.Department;
import com.cmcc.aregister.cs.model.UpdateEntity;
import com.cmcc.aregister.cs.util.UniqueKey;
import com.cmcc.aregister.cs.util.Utils;

@SuppressLint("NewApi")
public class ConfigUtilHelper extends ConfigUtil
{
    private static final String TAG = "ConfigUtilHelper";
    public static String one39Url = "http://shequ.10086.cn";
    public static String wuxianchengshi = "http://wap.szicity.com/index.php/city_xuan_news/";
    public static String yidongzhuanqu = "http://wap.szicity.com/cm/yezhi/index.aspx";
    public static String INFO_VISIBLE_PREFS = "info_visible_prefs";
    public static String info_visible_set = "is_info_visible_set";
    public static String IS_LOGIN = "is_login";
    /**
     * 必填，通过单向MD5 hash计算得出，表示如下： MD5(userId + password + timestamp)
     * 
     * @return
     */
    public static String getUserPwd()
    {
        String source = Arguments.userId + Arguments.userPwd + getStringNow();
        return getMD5(source.getBytes());
    }

    /**
     * 必填，通过单向MD5 hash计算得出，表示如下： MD5(userId + password + timestamp)
     * 
     * @return
     */
    public static String getAdUserPwd()
    {
        String source = Arguments.UserPwd_AD;
        return getMD5(source.getBytes());
    }

    /**
     * MD5加密算法
     * 
     * @param source
     * @return
     */
    public static String getMD5(byte[] source)
    {
        String s = null;
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f' };// 用来将字节转换成16进制表示的字符
        try
        {
            java.security.MessageDigest md = java.security.MessageDigest
                .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest();// MD5 的计算结果是一个 128 位的长整数，
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2];// 每个字节用 16 进制表示的话，使用两个字符， 所以表示成 16
            // 进制需要 32 个字符
            int k = 0;// 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++)
            {// 从第一个字节开始，对 MD5 的每一个字节// 转换成 16
             // 进制字符的转换
                byte byte0 = tmp[i];// 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,// >>>
                // 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf];// 取字节中低 4 位的数字转换

            }
            s = new String(str);// 换后的结果转换为字符串

        }
        catch (NoSuchAlgorithmException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 获取屏幕分辨率类型
     * 
     * @param a
     * @return
     */
    public static int getM(Activity a)
    {
        DisplayMetrics dm = new DisplayMetrics();

        a.getWindowManager().getDefaultDisplay().getMetrics(dm);

        int width = dm.widthPixels;

        int height = dm.heightPixels;
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "手机屏幕分辨率：" + width + "*" + height);
        }
        if (width == 320 && height == 480)
        {
            return 1;
        }
        else if (width == 480 && height == 800)
        {
            return 2;
        }
        else if (width == 480 && height == 854)
        {
            return 3;
        }
        else if (width == 540 && height == 960)
        {
            return 4;
        }
        else if (width == 720 && height == 1280)
        {
            return 5;
        }
        else if (width == 800 && height == 1280)
        {
            return 6;
        }
        return 0;
    }

    /* 获取版本号 */
    public static int getVersionCode(Application app)
    {
        PackageInfo packageInfo = null;
        try
        {
            packageInfo = app.getPackageManager().getPackageInfo(
                app.getPackageName(), 0);
            return packageInfo.versionCode;
        }
        catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 1;
    }

    /* 获取版本名称 */
    public static String getVersionName(Application app)
    {
        PackageInfo packageInfo = null;
        try
        {
            packageInfo = app.getPackageManager().getPackageInfo(
                app.getPackageName(), 0);
            return packageInfo.versionName;
        }
        catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取推送应用唯一标识
     * @param context
     * @return
     */
    public static String getAppKey(Context context)
    {
        ApplicationInfo appInfo = null;
        try
        {
            appInfo = context.getPackageManager().getApplicationInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
            String appkey = appInfo.metaData.getString("JPUSH_APPKEY");
            return appkey;
        }
        catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取推送渠道
     * @param context
     * @return
     */
    public static String getChannel(Context context)
    {
        ApplicationInfo appInfo = null;
        try
        {
            appInfo = context.getPackageManager().getApplicationInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
            String channel = appInfo.metaData.getString("JPUSH_CHANNEL");
            return channel;
        }
        catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 检查网络
     * 
     * @param c
     * @return
     */
    public static boolean isConnectingToInternet(Context c)
    {
        ConnectivityManager connectivity = (ConnectivityManager) c
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }

        }
        return false;
    }

    // 语音预约接口地址
    public static String voiceReqUrl = "http://wap.szicity.com/cm/yiliao/wxtest/index.php";
    // 登入接口url old "http://wap.szicity.com/api/login_3rd.php";
    public static String loginUrl = "http://wap.szicity.com/api/login_client.php";
    /**
     * 注销登陆接口
     */
    public static String logoutUrl = "http://wap.szicity.com/api/logout_client.php";

    // 获取动态码接口
    public static String getPwdUrl = "http://wap.szicity.com/api/Dynamic_password_create.php";
    /**
     * 获取图片验证码接口
     */
    public static String getVaildCode = "http://120.196.125.12/api/photo_validcode_create.php";
    /**
     * 验证图片验证码接口
     */
    public static String checkVaildCode = "http://120.196.125.12/api/photo_validcode_check.php";

    // 正式站
    // public static final String SERVER_URL_BASE =
    // "http://211.139.161.120/wxtest/api2/index.php?c=sch&a=";
    public static final String SERVER_URL_BASE = "http://120.196.125.19:19091/wxtest/api2/index.php?c=sch&a=";

    // **************家庭资料相关接口*************************************
    public static final String F_cid = "8";
    public static final String F_token = "wxcityMobileClient";
    public static final String FAMILY_URL_BASE = "http://120.196.125.19:19092/sch/JYSynServer/index.php?c=sch&a=";
    // 查询用户资料
    public static String getFamilyUrl = FAMILY_URL_BASE + "getFamily";
    // 修改家庭资料
    public static String updateFamily = FAMILY_URL_BASE + "updFamily";
    // 解除手机绑定
    public static String untiePhone = FAMILY_URL_BASE + "untiePhone";
    // *****************************************************************************

    // 注册接口
    public static String registUrl = SERVER_URL_BASE + "addMember";
    // 编辑用户信息
    public static String changeInfoUrl = SERVER_URL_BASE + "editMember";
    // 获取用户信息接口
    public static String getInfoUrl = SERVER_URL_BASE + "getMember";
    // 用户反馈接口
    public static String sendFeedbackMsgUrl = "http://wap.139.10086.cn:85/shenz/api.do?";

    public static final String loginId = "27";
    public static final String loginAuth = "b515eef74181c73446a10b53f9105450";

    public static final String url01 = "http://wap.szicity.com/cm/yidong/wap/API.aspx?function=index&SZYYTCT=TiYan&PID=1";
    public static final String url02 = "http://wap.szicity.com/cm/yidong/wap/API.aspx?function=index&SZYYTCT=TiYan&PID=8";
    public static final String url03 = "http://wap.szicity.com/cm/yidong/wap/API.aspx?function=index&SZYYTCT=TiYan&PID=4";

    public static boolean isShow = false;
    public static boolean isFromMain = false;
    public static Handler mHandler;

    /**
     * 这个请求报文方式已经过期（需要封装成xml形式进行请求，见 ConfigUtil下的postXml方法）
     * 
     * @param timestamp
     * @param msg_id
     * @param orderNo
     * @param amount
     * @param mobile
     * @param targetMobile
     * @param uid
     * @param token
     * @return
     */
    public static String requestPost(String timestamp, String msg_id,
        String orderNo, String amount, String mobile, String targetMobile,
        String uid, String token)
    {
        String xml = "";
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        HttpClient client = new DefaultHttpClient(httpParameters);

        HttpPost post = new HttpPost(payUrlPre);

        if (!Utils.isWifi())
        {
            String proxyHost = android.net.Proxy.getDefaultHost();
            if (proxyHost != null)
            {// 如果是wap方式，要加网关
                System.out.println(proxyHost);
                HttpHost proxy = new HttpHost("10.0.0.172", 80);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    proxy);
            }
        }

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("spID", spID));
        parameters.add(new BasicNameValuePair("spPwd", spPwd));
        parameters.add(new BasicNameValuePair("spCode", spCode));
        parameters.add(new BasicNameValuePair("spType", spType));
        parameters.add(new BasicNameValuePair("merchantCode", merchantCode));
        parameters.add(new BasicNameValuePair("timestamp", timestamp));
        parameters.add(new BasicNameValuePair("msg_id", msg_id));
        parameters.add(new BasicNameValuePair("orderNo", orderNo));
        parameters.add(new BasicNameValuePair("amount", amount));
        parameters.add(new BasicNameValuePair("mobile", mobile));
        parameters.add(new BasicNameValuePair("targetMobile", targetMobile));
        parameters.add(new BasicNameValuePair("merchantName", merchantName));
        parameters.add(new BasicNameValuePair("merchandise", merchandise));
        parameters.add(new BasicNameValuePair("orderDesc", orderDesc));
        parameters.add(new BasicNameValuePair("backUrl", backUrl));
        parameters.add(new BasicNameValuePair("uid", uid));
        parameters.add(new BasicNameValuePair("token", token));
        parameters.add(new BasicNameValuePair("payType", payType));
        try
        {
            post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200)
            {
                xml = EntityUtils.toString(response.getEntity());
            }

        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return xml;

    }

    /**
     * httpget请求
     * 
     * @param url
     * @return
     */
    public static String request(String url)
    {
        String outputString = null;
        String path = url;
        HttpGet httpGet = new HttpGet(path);
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        if (!Utils.isWifi())
        {
            String proxyHost = android.net.Proxy.getDefaultHost();
            if (proxyHost != null)
            {// 如果是wap方式，要加网关
                System.out.println(proxyHost);
                HttpHost proxy = new HttpHost("10.0.0.172", 80);
                httpClient.getParams().setParameter(
                    ConnRoutePNames.DEFAULT_PROXY, proxy);
            }
        }

        try
        {
            HttpResponse httpResp = httpClient.execute(httpGet);
            if (ConfigUtilHelper.debug)
            {
                Log.v(TAG, "getPath-->" + "5555555555555");
            }
            // 判断是够请求成功
            if (httpResp.getStatusLine().getStatusCode() == 200)
            {
                // 获取返回的数据
                outputString = EntityUtils.toString(httpResp.getEntity(),
                    "UTF-8");
                if (ConfigUtilHelper.debug)
                {
                    Log.i(TAG, outputString);
                }
            }
            else
            {
                if (ConfigUtilHelper.debug)
                {
                    Log.i(TAG, "HttpGet方式请求失败");
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            if (ConfigUtilHelper.debug)
            {
                Log.v(TAG, "请求异常");
            }
            e.printStackTrace();
        }
        httpClient.getConnectionManager().shutdown();
        return outputString;
    }

    public static String post(String url, String cid, String token,
        String version, String type) throws HttpResponseException,
        ClientProtocolException, IOException
    {
        String result = "";
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpPost post = new HttpPost(url);
        if (!Utils.isWifi())
        {
            String proxyHost = android.net.Proxy.getDefaultHost();
            if (proxyHost != null)
            {// 如果是wap方式，要加网关
                System.out.println(proxyHost);
                HttpHost proxy = new HttpHost("10.0.0.172", 80);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    proxy);
            }
        }
        List<NameValuePair> parameters = makeVersionParams(cid, token, version,
            type);
        try
        {
            post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200)
            {
                result = EntityUtils.toString(response.getEntity());
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        client.getConnectionManager().shutdown();
        return result;
    }

    /**
     * 组装版本控制接口请求参数
     * @param cid
     * @param token
     * @param version
     * @param type
     * @return
     */
    private static List<NameValuePair> makeVersionParams(String cid,
        String token, String version, String type)
    {
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("cid", cid));
        parameters.add(new BasicNameValuePair("token", token));
        parameters.add(new BasicNameValuePair("version", version));
        parameters.add(new BasicNameValuePair("type", type));
        return parameters;
    }

    /**
     * 检查更新
     * 
     * @param url
     * @return
     */
    public static UpdateEntity getUpdateMsg(String url, String cid,
        String token, String type, String version)
    {
        UpdateEntity entity = new UpdateEntity();
        String result = "";
        try
        {
            result = post(url, cid, token, version, type);
        }
        catch (HttpResponseException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        catch (ClientProtocolException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        catch (IOException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // result =
        // "{'state':'0','msg':'状态描述','data':{'VERSION_NUMBER':'版本号','CONTENT':'版本说明','STATE':'1 强制 0 不强制','DATETIME'：'时间','DOWN_LINK':'下载地址'}}";
        if (result != null)
        {
            try
            {
                JSONObject json = new JSONObject(result);
                entity.Status = json.getString("state");
                entity.Msg = json.getString("msg");
                if (entity.Status.equals("1"))
                {
                    JSONObject data = json.getJSONObject("data");
                    entity.VersionNum = data.getString("VERSION_NUMBER");
                    entity.Content = data.getString("CONTENT");
                    entity.State = data.getString("STATE");
                    entity.DateTime = data.getString("DATETIME");
                    entity.DownLink = data.getString("DOWN_LINK");
                }
            }
            catch (JSONException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return entity;
    }

    /**
     * 获取成员关系数组
     * 
     * @param context
     * @return {男性关系,男性关系值,女性关系,女性关系值}
     */
    public static Object[] getRelation(Context context)
    {
        String[] relation = context.getResources().getStringArray(
            R.array.member_relation);
        int[] relationValue = context.getResources().getIntArray(
            R.array.member_relation_value);
        String[] maleRelation = new String[relation.length / 2];
        int[] maleRelationValue = new int[relation.length / 2];
        String[] femaleRelation = new String[relation.length / 2];
        int[] femaleRelationValue = new int[relation.length / 2];
        for (int i = 0; i < relation.length; i++)
        {
            if (i % 2 == 0)
            {// 男性关系
                maleRelation[i / 2] = relation[i];
                maleRelationValue[i / 2] = relationValue[i];
            }
            else
            {// 女性关系
                femaleRelation[i / 2] = relation[i];
                femaleRelationValue[i / 2] = relationValue[i];
            }
        }
        return new Object[] { maleRelation, maleRelationValue, femaleRelation,
            femaleRelationValue };
    }

    /**
     * 获取关系的内容
     * 
     * @param context
     * @param relation
     * @return
     */
    public static String getRelationText(Context context, int relation, int sex)
    {
        String relationStr = "";
        if (relation == 1)
        {
            return "本人";
        }
        relation = convertRelation(relation, sex);
        String[] relationText = context.getResources().getStringArray(
            R.array.member_relation);
        int[] relationValue = context.getResources().getIntArray(
            R.array.member_relation_value);
        for (int i = 0; i < relationValue.length; i++)
        {
            if (relation == relationValue[i])
            {
                relationStr = relationText[i];
                break;
            }
        }
        return relationStr;
    }

    private static int convertRelation(int relation, int sex)
    {
        if (relation < 10)
        {// 原有关系
            switch (relation)
            {
            case 2:// 妻子
                relation = 15;
                break;
            case 3:// 丈夫
                relation = 14;
                break;
            case 4:// 儿女
                if (sex == 0)
                {// 男性
                    relation = 16;
                }
                else
                {// 女性
                    relation = 17;
                }
                break;
            case 5:// 孙子
                if (sex == 0)
                {// 男性
                    relation = 18;
                }
                else
                {// 女性
                    relation = 19;
                }
                break;
            case 6:// 爷爷
                relation = 10;
                break;
            case 7:// 奶奶
                relation = 11;
                break;
            }
        }
        return relation;
    }

    /**
     * 将原先的关系转换成现有关系，其中，儿女转成成儿子或女儿<br>
     * 原关系：1=妻子,2=丈夫,3=儿女,4=孙子,5=爷爷,6=奶奶<br>
     * 现关系：10=爷爷,11=奶奶,12=父亲,13=母亲,14=丈夫,15=妻子,16=儿子,17=女儿,18=孙子,19=孙女<br>
     * 
     * @param context
     * @param relation
     * @param sex
     * @return
     */
    public static int getRelationPosition(Context context, int relation, int sex)
    {
        int position = 0;
        relation = convertRelation(relation, sex);
        int[] relationValue = context.getResources().getIntArray(
            R.array.member_relation_value);
        for (int i = 0; i < relationValue.length; i++)
        {
            if (relation == relationValue[i])
            {
                position = i;
                break;
            }
        }
        return position;
    }

    /**
     * 判断是否为登陆状态
     * 
     * @param context
     * @return
     */
    public static boolean isLogin(Context context)
    {
        boolean isLogin = false;
        DatabaseAdapter mDatabaseAdapter = new DatabaseAdapter(context);
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null)
        {
            c.moveToFirst();
            if (c.getCount() > 0)
            {
                String date = c.getString(c.getColumnIndex("login_date"));
                try
                {
                    date = UniqueKey.decodeStr(date);
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String loginDate = new Date(Long.parseLong(date)).toString();
                long dateMillis = System.currentTimeMillis();
                String now = new Date(dateMillis).toString();
                SharedPreferences mSharedPreferences = context
                    .getSharedPreferences(ConfigUtilHelper.INFO_VISIBLE_PREFS,
                        Context.MODE_PRIVATE);
                Editor edit = mSharedPreferences.edit();
                if (ConfigUtilHelper.debug)
                {
                    Log.i(TAG, "now:" + now + "  loginDate:" + loginDate);
                }
                if (loginDate.equals(now))
                {
                    edit.putBoolean(ConfigUtilHelper.IS_LOGIN, true);
                    if (!ConfigUtilHelper.getUid(context).equals("")
                        && !ConfigUtilHelper.getToken(context).equals(""))
                    {
                        isLogin = true;
                    }
                }
                else
                {
                    edit.putBoolean(ConfigUtilHelper.IS_LOGIN, false);
                    String url = ConfigUtilHelper.logoutUrl + "?&id=" + ConfigUtilHelper.loginId
                        + "&auth=" + ConfigUtilHelper.loginAuth + "&mobile="
                        + ConfigUtilHelper.getMobile(context) + "&ostype=" + 2;
                    ConfigUtilHelper.request(url);
                }
                edit.commit();
            }
        }
        if (!isLogin)
        {// 未登录，清理用户信息
            mDatabaseAdapter.deleteAllUserData();
        }
        c.close();
        mDatabaseAdapter.close_user();
        return isLogin;
        // return false;
    }

    /**
     * 判断是否为注册用户
     * 
     * @param context
     * @return
     */
    public static boolean isRegister(Context context)
    {
        boolean isRegister = false;
        DatabaseAdapter mDatabaseAdapter = new DatabaseAdapter(context);
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null)
        {
            c.moveToFirst();
            if (c.getCount() > 0)
            {
                String date = c.getString(c.getColumnIndex("card"));
                try
                {
                    date = UniqueKey.decodeStr(date);
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (date != null && !date.equals(""))
                {
                    isRegister = true;
                }
            }
        }
        c.close();
        mDatabaseAdapter.close_user();
        return isRegister;
    }

    /**
     * 登陆成功后取得的手机号码
     * 
     * @param context
     * @return
     */
    public static String getMobile(Context context)
    {
        String mobile = "";
        DatabaseAdapter mDatabaseAdapter = new DatabaseAdapter(context);
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null && c.getCount() > 0)
        {
            c.moveToFirst();
            mobile = c.getString(c.getColumnIndex("mobile"));
            try
            {
                mobile = UniqueKey.decodeStr(mobile);
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        c.close();
        mDatabaseAdapter.close_user();
        return mobile;
    }

    /**
     * 登陆成功后取得的姓名
     * 
     * @param context
     * @return
     */
    public static String getUsername(Context context)
    {
        String username = "";
        DatabaseAdapter mDatabaseAdapter = new DatabaseAdapter(context);
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null && c.getCount() > 0)
        {
            c.moveToFirst();
            username = c.getString(c.getColumnIndex("username"));
            try
            {
                username = UniqueKey.decodeStr(username);
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        c.close();
        mDatabaseAdapter.close_user();
        return username;
    }

    /**
     * 清空手机号码
     * 
     * @param context
     * @return
     */
    public static String clearMobile(Context context)
    {
        String mobile = "";
        DatabaseAdapter mDatabaseAdapter = new DatabaseAdapter(context);
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null && c.getCount() > 0)
        {
            mDatabaseAdapter.deleteAllUserData();
        }
        c.close();
        mDatabaseAdapter.close_user();
        return mobile;
    }

    public static boolean isCard(String idNumber)
    {
        String pattern = "((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65|71|81|82|91)\\d{4})((((19|20)(([02468][048])|([13579][26]))0229))|((20[0-9][0-9])|(19[0-9][0-9]))((((0[1-9])|(1[0-2]))((0[1-9])|(1\\d)|(2[0-8])))|((((0[1,3-9])|(1[0-2]))(29|30))|(((0[13578])|(1[02]))31))))((\\d{3}(x|X))|(\\d{4}))";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(idNumber);
        return m.matches();
    }

    public static boolean isBirthAndCard(String card, String birth)
    {
        String b = card.substring(6, 14);
        String y = b.substring(0, 4);
        String m = b.substring(4, 6);
        String d = b.substring(6, 8);
        String[] births = birth.split("-");
        if (births[1].length() == 1)
        {
            births[1] = "0" + births[1];
        }
        if (births[2].length() == 1)
        {
            births[2] = "0" + births[2];
        }
        if (!births[0].equals(y) || !births[1].equals(m)
            || !births[2].equals(d))
        {
            return false;
        }
        return true;
    }

    public static String RMB_INFO = "remember_info";

    private static String RMB_MOBILE = "remember_mobile";
    private static String RMB_PWD = "remember_pwd";
    private static String RMB_PWD_FLAG = "remember_pwd_flag";
    private static String AUTO_LOGIN_FLAG = "auto_login_flag";
    private static String NOTICE_ID = "notice_id";

    private static String UID = "uid";
    private static String TOKEN = "token";
    private static String STIME = "stime";// 开始时间
    private static String ETIME = "etime";// 结束时间
    private static String NETWORK = "NETWORK";// 网络状态
    private static String LLTongji = "lltongji";
    public static final int G2_G3 = 1;
    public static final int WIFI = 2;

    // 创建SharePreference
    public static SharedPreferences getInfoSharedPreferences(Context c)
    {
        return c.getSharedPreferences(RMB_INFO, Context.MODE_PRIVATE);
    }

    /**
     * 获取网络状态
     * 
     * @param c
     * @return
     */
    public static int getNetworkState(Context c)
    {
        return getInfoSharedPreferences(c).getInt(NETWORK, WIFI);
    }

    /**
     * 存储网络状态
     * 
     * @param c
     * @param state
     */
    public static void saveNetworkState(Context c, int state)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putInt(NETWORK, state);
        localEditor.commit();
    }

    /**
     * 获取流量
     * 
     * @param c
     * @return
     */
    public static long getLiuliang(Context c)
    {
        return getInfoSharedPreferences(c).getLong(LLTongji, 0);
    }

    /**
     * 存储流量
     * 
     * @param c
     * @param liuliang
     */
    public static void saveLiuliang(Context c, long liuliang)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putLong(LLTongji, liuliang);
        localEditor.commit();
    }

    /**
     * 清理流量
     * 
     * @param c
     */
    public static void clearLiuliang(Context c)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.remove(LLTongji);
        // localEditor.clear();
        localEditor.commit();
    }

    /**
     * 获取开始时间
     * 
     * @param c
     * @return
     */
    public static long getStime(Context c)
    {
        return getInfoSharedPreferences(c).getLong(STIME, 0);
    }

    /**
     * 存储开始时间
     * 
     * @param c
     * @param liuliang
     */
    public static void saveStime(Context c, long stime)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putLong(STIME, stime);
        localEditor.commit();
    }

    /**
     * 获取结束时间
     * 
     * @param c
     * @return
     */
    public static long getEtime(Context c)
    {
        return getInfoSharedPreferences(c).getLong(ETIME, 0);
    }

    /**
     * 存储结束时间
     * 
     * @param c
     * @param liuliang
     */
    public static void saveEtime(Context c, long etime)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putLong(ETIME, etime);
        localEditor.commit();
    }

    // 获取记住的手机
    public static String getMobileNum(Context c)
    {
        String str = getInfoSharedPreferences(c).getString(RMB_MOBILE, "");
        try
        {
            str = UniqueKey.decodeStr(str);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    public static boolean has_regist = false;

    // 存储记住的手机号码
    public static void saveMobileSharedPreferences(Context c, String mobile)
    {
        try
        {
            mobile = UniqueKey.encodeStr(mobile);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putString(RMB_MOBILE, mobile);
        localEditor.commit();
    }

    // 获取记住的密码
    public static String getServicePwd(Context c)
    {
        String str = getInfoSharedPreferences(c).getString(RMB_PWD, "");
        try
        {
            str = UniqueKey.decodeStr(str);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    // 存储密码
    public static void savePwdSharedPreferences(Context c, String pwd)
    {
        try
        {
            pwd = UniqueKey.encodeStr(pwd);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putString(RMB_PWD, pwd);
        localEditor.commit();
    }

    public static void saveLastNoticeId(Context c, int id)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putInt(NOTICE_ID, id);
        localEditor.commit();
    }

    public static int getLastNoticeId(Context c)
    {
        return getInfoSharedPreferences(c).getInt(NOTICE_ID, 0);
    }

    // 获取是否自动登陆
    public static boolean getAutoLogin(Context c)
    {
        return getInfoSharedPreferences(c).getBoolean(AUTO_LOGIN_FLAG, false);
        // return true;
    }

    // 存储自动登录
    public static void saveAutoLogin(Context c, boolean isAutoLogin)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putBoolean(AUTO_LOGIN_FLAG, isAutoLogin);
        localEditor.commit();
    }

    // 获取是否记住密码
    public static boolean getRmbPwdFlag(Context c)
    {
        return getInfoSharedPreferences(c).getBoolean(RMB_PWD_FLAG, false);
    }

    // 存储记住密码
    public static void saveRmbPwdFlag(Context c, boolean isRmbPwd)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putBoolean(RMB_PWD_FLAG, isRmbPwd);
        localEditor.commit();
    }

    // 获取uid
    public static String getUid(Context c)
    {
        String str = getInfoSharedPreferences(c).getString(UID, "");
        try
        {
            str = UniqueKey.decodeStr(str);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    // 存储uid
    public static void saveUid(Context c, String uid)
    {
        try
        {
            uid = UniqueKey.encodeStr(uid);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putString(UID, uid);
        localEditor.commit();
    }

    // 获取token
    public static String getToken(Context c)
    {
        String str = getInfoSharedPreferences(c).getString(TOKEN, "");
        try
        {
            str = UniqueKey.decodeStr(str);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    // 存储token
    public static void saveToken(Context c, String token)
    {
        try
        {
            token = UniqueKey.encodeStr(token);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.putString(TOKEN, token);
        localEditor.commit();
    }

    // 清空手机和密码数据
    public static void removeData(Context c)
    {
        SharedPreferences.Editor localEditor = getInfoSharedPreferences(c)
            .edit();
        localEditor.clear();
        localEditor.commit();
    }

    public static boolean isMobileNum11(String mobiles)
    {
        Pattern p = Pattern
            .compile("^((13[0-9])|(15[^4,\\D])|(18[^4,\\D])|(147))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断传入的字符串是否不为空
     * 
     * @param str
     * @return 传入的字符串不为空返回true，反之返回false
     */
    public static boolean isNotEmpty(String str)
    {
        if (str != null && !"".equalsIgnoreCase(str))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    // 判断是否为移动的号码
    public static boolean isMobileNum(String mobile)
    {
        // String str_2 = mobile.substring(0, 2);
        String str_3 = mobile.substring(0, 3);
        if (str_3.equals("134"))
        {
            String str_4 = mobile.substring(0, 4);
            if (str_4.equals("1340") || str_4.equals("1341")
                || str_4.equals("1342") || str_4.equals("1343")
                || str_4.equals("1344") || str_4.equals("1345")
                || str_4.equals("1346") || str_4.equals("1347")
                || str_4.equals("1348"))
            {
                return true;
            }
        }
        if (str_3.equals("135") || str_3.equals("136") || str_3.equals("137")
            || str_3.equals("138") || str_3.equals("139")
            || str_3.equals("147") || str_3.equals("150")
            || str_3.equals("151") || str_3.equals("152")
            || str_3.equals("157") || str_3.equals("158")
            || str_3.equals("159") || str_3.equals("182")
            || str_3.equals("183") || str_3.equals("187")
            || str_3.equals("188"))
        {
            return true;
        }
        return false;
    }

    // 获得随机数
    public static String getRandom(int max)
    {
        StringBuffer str = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < max; i++)
        {
            int r = Math.abs(random.nextInt()) % 10;
            str.append(r);
        }
        return str.toString();
    }

    // 获取平台流水号,当前时间+4位随机数
    public static String getMsgId()
    {
        StringBuffer str = new StringBuffer();
        str.append(getStringNow());
        str.append(getRandom(4));
        return str.toString();
    }

    // 获取订单号,当前时间+六位随机数
    public static String _getOrderNo()
    {
        StringBuffer str = new StringBuffer();
        str.append(getStringNow());
        str.append(getRandom(6));
        return str.toString();
    }

    /**
     * 判断网络连接
     * 
     * @param c
     * @return
     */
    public static int checkNetworkState(Context c)
    {
        boolean flag = false;
        ConnectivityManager manager = (ConnectivityManager) c
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .getState();
        State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .getState();
        // 如果3G、wifi、2G等网络状态是连接的，则退出，否则显示提示信息进入网络设置界面
        if (mobile == State.CONNECTED || mobile == State.CONNECTING)// 2g/3g
            return 1;
        if (wifi == State.CONNECTED || wifi == State.CONNECTING)// wifi
            return 2;
        return 0;// 没有就不统计
    }

    // 获取订单号,当前时间14位
    /*
     * public static String getOrderNo(){ StringBuffer str = new StringBuffer();
     * str.append(getStringNow()); return str.toString(); }
     */
    /**
     * 计算当前流量
     * 
     * @param c
     */
    public static long countCurrentLiuliang(Context c)
    {
        int appid = ConfigUtil.getUids(c);
        long rxdata = TrafficStats.getUidRxBytes(appid);// 该程序下载流量
        long txdata = TrafficStats.getUidTxBytes(appid);// 该程序上传流量
        long data_total = rxdata + txdata; // 该程序总的流量
        return data_total;
    }

    @SuppressLint("NewApi")
    public static void countLiuliang(Context c)
    {
        int appid = ConfigUtil.getUids(c);
        // ConfigUtil.getUids(c);
        long rxdata = TrafficStats.getUidRxBytes(appid);// 该程序下载流量
        long txdata = TrafficStats.getUidTxBytes(appid);// 该程序上传流量
        long data_total = rxdata + txdata; // 该程序总的流量
        // long liuliang = ConfigUtilHelper.getLiuliang(c);
        long l = data_total - MyApplication.startLiuliang;
        try
        {
            if (l > 0)
            {
                ConfigUtilHelper.saveLiuliang(c, l);
            }
            else
            {
                ConfigUtilHelper.saveLiuliang(c, 0);
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }

    }

    public static String merchantId = "303310048990001";
    public static String merchantOrderId = "2012061314538888";
    public static String merchantOrderTime = "20120613145312";
    public static String sign = "caY7bEjLVzQaS38fkWmjhdhreFCguWOcuO8/ftpdywlzXSj3qFxMyIQIsJngVRk9o2xHRsTSfRR4L7E071vyU1xfye+w4uOSbuyrsnZjb4aWzFiTcgdSDjJaSeVR3KurHjJ2wIem+ZiSU9I8mlqQmMrGvw2iAkY7OoH54zolK14=";

    public static String xml = "<?xml version='1.0' encoding='UTF-8' ?><upomp application='LanchPay.Req' version='1.0.0'><merchantId>303310048990001</merchantId><merchantOrderId>2012061314538888</merchantOrderId><merchantOrderTime>20120613145312</merchantOrderTime><sign>caY7bEjLVzQaS38fkWmjhdhreFCguWOcuO8/ftpdywlzXSj3qFxMyIQIsJngVRk9o2xHRsTSfRR4L7E071vyU1xfye+w4uOSbuyrsnZjb4aWzFiTcgdSDjJaSeVR3KurHjJ2wIem+ZiSU9I8mlqQmMrGvw2iAkY7OoH54zolK14=</sign></upomp>";
}
